package cn.com.yx.ms.service.impl;

import cn.com.yx.ms.application.web.ApiQueryBase;
import cn.com.yx.ms.domain.TreeModel;
import cn.com.yx.ms.domain.dbmodel.*;
import cn.com.yx.ms.domain.mq.MqPushProgramModel;
import cn.com.yx.ms.domain.mq.MqSelectedDevModel;
import cn.com.yx.ms.domain.mq.MqSelectedProgramModel;
import cn.com.yx.ms.domain.program.*;
import cn.com.yx.ms.persistence.*;
import cn.com.yx.ms.service.ILogService;
import cn.com.yx.ms.service.IProgramService;
import cn.com.yx.ms.service.IUserContextService;
import cn.yx.framework.configuration.ApiCode;
import cn.yx.framework.configuration.AppConstant;
import cn.yx.framework.configuration.BaseConstant;
import cn.yx.framework.context.UserContext;
import cn.yx.framework.util.DateUtil;
import cn.yx.framework.view.ApiResult;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * ApphubServiceImpl
 */
@Service
@Transactional
public class ProgramServiceImpl implements IProgramService {

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private ILogService iLogService;
    @Resource
    private IUserContextService iUserContextService;
    @Resource
    private ScCatalogMapper scCatalogMapper;
    @Resource
    private ScFileMapper scFileMapper;
    @Resource
    private JmProgramMapper jmProgramMapper;
    @Resource
    private JmProgramFileMapMapper jmProgramFileMapMapper;
    @Resource
    private JmDevProgramMapMapper jmDevProgramMapMapper;
    @Resource
    private GgCatalogMapper ggCatalogMapper;
    @Resource
    private JmMainMapper jmMainMapper;
    @Resource
    private JmScMapMapper jmScMapMapper;
    @Resource
    private ScLiveMapper scLiveMapper;


    //region << 素材目录管理 >>
    @Override
    public ApiResult saveScCatalog(CatalogModel scCatalogModel) {
        ApiResult result = null;


        if (!StringUtils.isNoneBlank(scCatalogModel.getName())) {
            result = new ApiResult(AppConstant.MSG_FAILURE, false, "目录名称不能为空");
        }


        //判断同级下目录名称是否重复
        int countByName = scCatalogMapper.selectCountByCatalogName(scCatalogModel.getParentid(), scCatalogModel.getName());
        if (!StringUtils.isNoneBlank(scCatalogModel.getId()) && countByName > 0) {
            result = new ApiResult(AppConstant.MSG_FAILURE, false, "同级目录下目录名不能重复，请重新输入");
        }

        ScCatalog scCatalog = scCatalogMapper.selectByPrimaryKey(scCatalogModel.getId());
        if (scCatalog == null) {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "", insertScCatalog(scCatalogModel));

        } else {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "", updateScCatalog(scCatalogModel));

        }

        return result;
    }

    @Override
    public int insertScCatalog(CatalogModel scCatalogModel) {
        ScCatalog scCatalog = new ScCatalog();

        if (!StringUtils.isNoneBlank(scCatalogModel.getId())) {
            scCatalogModel.setId(UUID.randomUUID().toString());
        }

        scCatalog.setGuid(scCatalogModel.getId());
        scCatalog.setName(scCatalogModel.getName());
        scCatalog.setParentid(scCatalogModel.getParentid());
        scCatalog.setLevel(0);
        scCatalog.setNumber(scCatalogMapper.getMaxNumber(scCatalogModel.getParentid()));
        scCatalog.setOrderindex(scCatalogModel.getOrderindex());
        scCatalog.setCreatetime(new Date());
        scCatalog.setUpdatetime(new Date());
        scCatalog.setIsdeleted(0);
        int result = scCatalogMapper.insert(scCatalog);

        if (result > 0) {
            iLogService.log("info",
                    "素材目录管理",
                    "创建成功-【" + JSON.toJSONString(scCatalog) + "】",
                    iUserContextService.getUserContext().getId());
        }

        return result;
    }

    @Override
    public ApiResult deleteScCatalog(String id) {
        //int result = scCatalogMapper.deleteByPrimaryKey(id);
        ApiResult result = null;
        int count = 0;

        ScCatalog scCatalog = scCatalogMapper.selectByPrimaryKey(id);
        if (scCatalog != null) {
            //判断公告目录是否存在子节点
            List<ScCatalog> childs = scCatalogMapper.findChild(id);
            if (childs != null && childs.size() > 0) {
                return new ApiResult(AppConstant.MSG_FAILURE, false, "存在子目录，不允许删除");
            }

            scCatalog.setIsdeleted(1);
            count = scCatalogMapper.updateByPrimaryKey(scCatalog);

            //删除目录下对应的公告内容
            ApiQueryBase query = new ApiQueryBase();
            query.setConditions(new HashMap<String, Object>());
            query.getConditions().put("catalogid", scCatalog.getGuid());
            List<ScFile> scFiles = scFileMapper.find(query);
            if (scFiles != null && scFiles.size() > 0) {
                for (int i = 0; i < scFiles.size(); i++) {
                    scFiles.get(i).setIsdeleted(1);
                    scFileMapper.updateByPrimaryKey(scFiles.get(i));
                }
            }

            if (count > 0) {
                iLogService.log("info",
                        "素材目录管理",
                        "删除成功-【" + id + "】-【" + scCatalog.getName() + "】",
                        iUserContextService.getUserContext().getId());
            }
        }


        result = new ApiResult(AppConstant.MSG_SUCCESS, true, "删除成功");
        return result;
    }

    @Override
    public int updateScCatalog(CatalogModel scCatalogModel) {
        ScCatalog scCatalog = scCatalogMapper.selectByPrimaryKey(scCatalogModel.getId());
        scCatalog.setName(scCatalogModel.getName());
        scCatalog.setOrderindex(scCatalogModel.getOrderindex());
        scCatalog.setUpdatetime(new Date());
        scCatalog.setIsdeleted(0);
        int result = scCatalogMapper.updateByPrimaryKey(scCatalog);
        if (result > 0) {
            iLogService.log("info",
                    "素材目录管理",
                    "修改成功-【" + JSON.toJSONString(scCatalog) + "】",
                    iUserContextService.getUserContext().getId());
        }
        return result;
    }

    @Override
    public List<CatalogModel> findScCatalogs(ApiQueryBase apiQueryBase) {
        ScCatalog scCatalog = null;//scCatalogMapper.selectByPrimaryKey("root");
        List<ScCatalog> scCatalogs = scCatalogMapper.find(apiQueryBase);
        List<CatalogModel> scCatalogModels = new ArrayList<CatalogModel>();

        for (ScCatalog catalog : scCatalogs) {
            if (!StringUtils.isNoneBlank(catalog.getParentid())) {
                scCatalog = catalog;
                break;
            }
        }

        //初始化根节点
        CatalogModel root = new CatalogModel();
        root.setId(scCatalog.getGuid());
        root.setName(scCatalog.getName());
        root.setNumber(scCatalog.getNumber());
        root.setChildren(new ArrayList<CatalogModel>());
        root.setIcon("/static/img/folder.png");
        root.setIconOpen("/static/img/folderOpen.png");


        BuildScCatalogTree(root, scCatalogs);

        if (root.getChildren() != null && root.getChildren().size() != 0) {
            root.setIsleaf(0);
        } else {
            root.setIsleaf(1);
        }

        scCatalogModels.add(root);
        return scCatalogModels;
    }

    private void BuildScCatalogTree(CatalogModel node, List<ScCatalog> scCatalogs) {
        for (ScCatalog scCatalog :
                scCatalogs) {
            if (scCatalog.getParentid() != null && scCatalog.getParentid().equals(node.getId())) {
                CatalogModel child = new CatalogModel();
                child.setId(scCatalog.getGuid());
                child.setName(scCatalog.getName());
                child.setParentid(scCatalog.getParentid());
                child.setNumber(scCatalog.getNumber());

                child.setOrderindex(scCatalog.getOrderindex());
                child.setChildren(new ArrayList<CatalogModel>());
                child.setIcon("/static/img/folder.png");
                child.setIconOpen("/static/img/folderOpen.png");
                node.getChildren().add(child);

                //递归调用
                BuildScCatalogTree(child, scCatalogs);
                if (child.getChildren() != null && child.getChildren().size() != 0) {

                    child.setIsleaf(0);
                } else {
                    child.setIsleaf(1);
                }
            }

        }

    }

    @Override
    public CatalogModel findScCatalog(String id) {
        CatalogModel scCatalogModel = null;
        ScCatalog scCatalog = scCatalogMapper.selectByPrimaryKey(id);
        if (scCatalog != null) {
            scCatalogModel = new CatalogModel();
            scCatalogModel.setId(scCatalog.getGuid());
            scCatalogModel.setParentid(scCatalog.getParentid());
            scCatalogModel.setName(scCatalog.getName());
            scCatalogModel.setOrderindex(scCatalog.getOrderindex());
        }
        return scCatalogModel;
    }

    //endregion

    // region << 素材管理 >>

    @Override
    public ApiResult saveScFile(ScFileModel scFileModel) {
        ApiResult result = null;


        if (!StringUtils.isNoneBlank(scFileModel.getFilename())) {
            result = new ApiResult(AppConstant.MSG_FAILURE, false, "请输入文件名");
            return result;
        }


        //文件MD5是否重复
        if (!StringUtils.isNoneBlank(scFileModel.getLiveurl())) {
            int countByEname = scFileMapper.selectCountByMd5(scFileModel.getMd5());
            if (!StringUtils.isNoneBlank(scFileModel.getGuid()) && countByEname > 0) {
                result = new ApiResult(AppConstant.MSG_FAILURE, false, "该文件已存在，请重新输入");
                return result;
            }
        }

        if (!StringUtils.isNoneBlank(scFileModel.getGuid())) {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "", insertScFile(scFileModel));

        } else {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "", updateScFile(scFileModel));
        }

        return result;
    }

    @Override
    public int insertScFile(ScFileModel scFileModel) {

        ScFile scFile = new ScFile();

        if (!StringUtils.isNoneBlank(scFileModel.getGuid())) {
            scFileModel.setGuid(UUID.randomUUID().toString());
        }

        scFile.setGuid(scFileModel.getGuid());
        scFile.setFolderid(scFileModel.getCatalogid());
        scFile.setFilename(scFileModel.getFilename());
        scFile.setFiletype(scFileModel.getFiletype());
        scFile.setFilesize(scFileModel.getFilesize());
        scFile.setMd5(scFileModel.getMd5());
        scFile.setFilepath(scFileModel.getFilepath());
        scFile.setCreatetime(new Date());
        //scFile.setCreatetime(DateUtil.string2Date(scFileModel.getCreatetime(), "yyyy-MM-dd HH:mm:ss.SSS"));
        scFile.setCreateuserid("");
        scFile.setIsdeleted(0);
        scFile.setOrderindex(0);
        if (StringUtils.isNoneBlank(scFileModel.getLiveurl())) {
            scFile.setLiveurl(scFileModel.getLiveurl());
            scFile.setFiletype("live");
        }


        //保存素材信息
        int result = scFileMapper.insert(scFile);
        if (result > 0) {
            iLogService.log("info",
                    "素材管理",
                    "创建成功-【" + JSON.toJSONString(scFile) + "】",
                    iUserContextService.getUserContext().getId());
        }
        return result;
    }

    @Override
    public int deleteScFile(String id) {
        // int result = scFileMapper.deleteByPrimaryKey(id);

        int result = 0;
        ScFile scFile = scFileMapper.selectByPrimaryKey(id);
        if (scFile != null) {
            scFile.setIsdeleted(1);
            scFile.setMd5("");
            result = scFileMapper.updateByPrimaryKey(scFile);

            // 更新关系表
            jmProgramFileMapMapper.updateMapByResourceId(id);

            if (result > 0) {
                iLogService.log("info",
                        "素材管理",
                        "删除成功-【" + id + "】-【" + scFile.getFilename() + "】",
                        iUserContextService.getUserContext().getId());
            }
        }


        return result;
    }

    @Override
    public int updateScFile(ScFileModel scFileModel) {
        ScFile scFile = scFileMapper.selectByPrimaryKey(scFileModel.getGuid());
        scFile.setFilename(scFileModel.getFilename());
        scFile.setLiveurl(scFileModel.getLiveurl());
        int result = scFileMapper.updateByPrimaryKey(scFile);
        if (result > 0) {
            iLogService.log("info",
                    "素材管理",
                    "修改成功-【" + JSON.toJSONString(scFile) + "】",
                    iUserContextService.getUserContext().getId());
        }
        return result;
    }


    @Override
    public List<ScFile> findScFiles(ApiQueryBase apiQueryBase) {
        return scFileMapper.find(apiQueryBase);
    }

    @Override
    public ScFileModel findScFile(String id) {
        ScFileModel scFileModel = null;
        ScFile scFile = scFileMapper.selectByPrimaryKey(id);
        if (scFile != null) {
            scFileModel = new ScFileModel();
            scFileModel.setGuid(scFile.getGuid());
            scFileModel.setCatalogid(scFile.getFolderid());
            scFileModel.setFilename(scFile.getFilename());
            scFileModel.setFiletype(scFile.getFiletype());
            scFileModel.setMd5(scFile.getMd5());
            scFileModel.setFilepath(scFile.getFilepath());
            scFileModel.setCreatetime(DateUtil.date2String(scFile.getCreatetime(), "yyyy-MM-dd HH:mm:ss"));
            scFileModel.setLiveurl(scFile.getLiveurl());
        }
        return scFileModel;
    }

    @Override
    public int selectCountByMd5(String md5) {
        return scFileMapper.selectCountByMd5(md5);
    }

    @Override
    public int saveFiles(String folderid, List<UploadFileModel> uploadFileModels, HttpServletRequest request) {
        int result = 0;

        if (uploadFileModels != null && uploadFileModels.size() > 0) {
            for (UploadFileModel uploadfileModel : uploadFileModels) {
                ScFile scFile = new ScFile();
                scFile.setGuid(UUID.randomUUID().toString());
                scFile.setFolderid(folderid);
                scFile.setFilename(uploadfileModel.getName());
                scFile.setFiletype(uploadfileModel.getType());
                scFile.setFilesize(uploadfileModel.getOrigSize());
                scFile.setMd5(uploadfileModel.getHash());

                String yearMonth = DateUtil.date2String(new Date(), "yyyyMM");
                scFile.setFilepath(yearMonth + "/" + uploadfileModel.getId() + uploadfileModel.getName().substring(uploadfileModel.getName().lastIndexOf(".")));

                scFile.setCreatetime(new Date());
                scFile.setCreateuserid("");
                scFile.setIsdeleted(0);
                scFile.setOrderindex(0);

                scFileMapper.insert(scFile);
                result++;
            }
        }


        if (result > 0) {
            UserContext userContext = (UserContext) redisTemplate.opsForValue().get(request.getParameter("sessionid"));
            iLogService.log("info",
                    "素材管理",
                    "上传成功：目录【" + folderid + "】，数量【" + result + "】，上传内容【" + JSON.toJSONString(uploadFileModels) + "】",
                    userContext.getId());
        }

        return result;
    }

    /**
     * 素材目录树做成
     *
     * @return
     */
    @Override
    public List<TreeModel> findCatalogFileTree() {
        CatalogFileModel catalogFileModel = null;
        List<TreeModel> treeModels = new ArrayList<TreeModel>();
        List<CatalogFileModel> catalogFileModels = scFileMapper.findCatalogFile();


        for (CatalogFileModel cfm : catalogFileModels) {
            if (cfm.getGuid().equals("root")) {
                catalogFileModel = cfm;
                break;
            }
        }

        //初始化根节点
        TreeModel root = new TreeModel();
        root.setId(catalogFileModel.getGuid());
        root.setName(catalogFileModel.getName());
        root.setNodetype(catalogFileModel.getNodetype());
        root.setChildren(new ArrayList<TreeModel>());
        root.setResourcetype(catalogFileModel.getResourcetype());


        BuildCatalogFileTree(root, catalogFileModels);


        treeModels.add(root);
        return treeModels;
    }

    /**
     * 公告目录树做成
     *
     * @return
     */
    @Override
    public List<TreeModel> findGgFileTree() {
        CatalogFileModel catalogFileModel = null;
        List<CatalogFileModel> catalogFileModels = ggCatalogMapper.findCatalogFile();
        List<TreeModel> treeModels = new ArrayList<TreeModel>();

        for (CatalogFileModel cfm : catalogFileModels) {
            if (cfm.getGuid().equals("root")) {
                catalogFileModel = cfm;
                break;
            }
        }
        //初始化根节点
        TreeModel root = new TreeModel();
        root.setId(catalogFileModel.getGuid());
        root.setName(catalogFileModel.getName());
        root.setNodetype(catalogFileModel.getNodetype());
        root.setChildren(new ArrayList<TreeModel>());

        BuildCatalogFileTree(root, catalogFileModels);


        treeModels.add(root);
        return treeModels;
    }

    private void BuildCatalogFileTree(TreeModel node, List<CatalogFileModel> catalogFileModels) {

        for (CatalogFileModel catalogFileModel :
                catalogFileModels) {
            if (catalogFileModel.getParentid() != null && catalogFileModel.getParentid().equals(node.getId())) {

                TreeModel child = new TreeModel();
                child.setId(catalogFileModel.getGuid());
                child.setName(catalogFileModel.getName());
                child.setParentid(catalogFileModel.getParentid());
                child.setNodetype(catalogFileModel.getNodetype());
                child.setResourcetype(catalogFileModel.getResourcetype());
                child.setFilepath(catalogFileModel.getFilepath());
                if (catalogFileModel.getResourcetype().indexOf("video") != -1) {
                    child.setIcon("/static/img/video.png");
                } else if (catalogFileModel.getResourcetype().indexOf("image") != -1) {
                    child.setIcon("/static/img/image.png");
                } else if (catalogFileModel.getResourcetype().indexOf("live") != -1) {
                    child.setIcon("/static/img/live.png");
                } else if (catalogFileModel.getResourcetype().indexOf("notice") != -1) {
                    child.setIcon("/static/img/notice.png");
                }
                child.setChildren(new ArrayList<TreeModel>());
                node.getChildren().add(child);
                //递归调用
                BuildCatalogFileTree(child, catalogFileModels);

            }
        }

        if (node.getNodetype().equals("0")) {
            node.setIsParent("true");
        } else {
            node.setIsParent("false");
        }

    }
    // endregion

    // region << 节目管理 >>

    /**
     * 保存节目
     *
     * @param programModel
     * @return
     */
    @Override
    public ApiCode saveProgram(ProgramModel programModel) {
        ApiCode apiCode = ApiCode.APP_100200;
        if (!StringUtils.isNoneBlank(programModel.getTitle())) {
            apiCode = ApiCode.APP_301501;
            // result = new ApiResult(AppConstant.MSG_FAILURE, false, "请输入节目标题");
            return apiCode;
        }
        //合并视频和公告集合
        List<ResourceFileModel> jmScMaps = programModel.getJmScMaps();
        List<ResourceFileModel> jmGgMaps = programModel.getJmGgMaps();
        jmScMaps.addAll(jmGgMaps);
        programModel.setJmScMaps(jmScMaps);

        if (!StringUtils.isNoneBlank(programModel.getGuid())) {
            //System.out.println("进入了这里");
            if (insertProgram(programModel) == 0) {
                //System.out.println("保存节目失败");
                apiCode = ApiCode.APP_301500;

                //return new ApiResult().success(AppConstant.MSG_FAILURE, "保存节目失败", null);
            } else {
                //System.out.println("进入创建节目信息");
                apiCode = ApiCode.APP_300500;

                //return new ApiResult().success(AppConstant.MSG_SUCCESS, "创建节目成功", null);
            }
        } else {
            if (updateProgram(programModel) == 0) {
                //System.out.println("更新节目失败");
                apiCode = ApiCode.APP_301500;
                //请添加素材

                //return new ApiResult().success(AppConstant.MSG_FAILURE, "更新节目失败", null);
            } else {
                //System.out.println("更新节目成功");
                apiCode = ApiCode.APP_300501;

                //return new ApiResult().success(AppConstant.MSG_SUCCESS, "更新节目成功", null);
            }
        }
        return apiCode;
    }

    /**
     * 创建节目
     *
     * @param programModel
     * @return
     */
    @Override
    public int insertProgram(ProgramModel programModel) {
//        int count = 0;
//        JmProgram jmProgram = new JmProgram();
//
//        if (!StringUtils.isNoneBlank(programModel.getGuid())) {
//            programModel.setGuid(UUID.randomUUID().toString());
//        }
//
//        jmProgram.setGuid(programModel.getGuid());
//        jmProgram.setTitle(programModel.getTitle());
//        jmProgram.setCreatetime(new Date());
//        jmProgram.setCreateuserid(programModel.getCreateuserid());
//        jmProgram.setMemo(programModel.getMemo());
//        jmProgram.setType(0);
//
//        //保存节目信息
//        count = jmProgramMapper.insert(jmProgram);
//
//        //保存节目素材关系
//        saveProgramFile(programModel);
//
//        if (count > 0) {
//            iLogService.log("info",
//                    "节目管理",
//                    "创建成功-【" + JSON.toJSONString(jmProgram) + "】",
//                    iUserContextService.getUserContext().getId());
//        }
        JmMain jmMain = new JmMain();

        String guid = UUID.randomUUID().toString();
        jmMain.setGuid(guid);
        jmMain.setTitle(programModel.getTitle());
        jmMain.setCreatetime(new Date());
        jmMain.setCreateuserid(programModel.getCreateuserid());
        jmMain.setSort(programModel.getSort());
        if (programModel.isIshaslive()) {
            jmMain.setDefaultchannelno(programModel.getDefaultchannelno());
        } else {
            jmMain.setDefaultchannelno(null);
        }

        // 添加节目主体
        int rt = jmMainMapper.insertSelective(jmMain);
        if (rt > 0) {
            List<ResourceFileModel> list = programModel.getJmScMaps();

            // 未添加素材的场合
            if (null == list || list.size() == 0) {
                return 0;
            }
            for (ResourceFileModel map : list) {
                map.setGuid(UUID.randomUUID().toString());
                map.setJmid(guid);
            }

            rt = jmScMapMapper.insertMapList(list);

            if (rt == list.size()) {
//                iLogService.log("info",
//                        "节目管理",
//                        "创建成功-【" + JSON.toJSONString(jmMain) + "】");
//                        iUserContextService.getUserContext().getId());
            }
        }
        //修改公告的rtype=3;
        jmScMapMapper.updateRtype();
        return rt;
    }

    @Override
    public int deleteProgram(String id) {
        int count = 0;
        //JmProgram jmProgram = jmProgramMapper.selectByPrimaryKey(id);
        JmMain jmMain = jmMainMapper.selectByPrimaryKey(id);

        if (jmMain != null) {
            //count = jmProgramFileMapMapper.deleteByProgramId(id);
            count = jmScMapMapper.deleteByPrimaryKey(id);
            count += jmMainMapper.deleteByPrimaryKey(id);

            // count += jmProgramMapper.deleteByPrimaryKey(id);
            if (count > 0) {

                iLogService.log("info",
                        "节目管理",
                        "删除成功-【" + id + "】-【" + jmMain.getTitle() + "】",
                        iUserContextService.getUserContext().getId());
            }
        }
        return count;
    }

    /**
     * 更新节目
     *
     * @param programModel
     * @return
     */
    @Override
    public int updateProgram(ProgramModel programModel) {
        JmMain jmMain = new JmMain();

        jmMain.setGuid(programModel.getGuid());
        jmMain.setTitle(programModel.getTitle());
        jmMain.setSort(programModel.getSort());
        if (programModel.isIshaslive()) {
            jmMain.setDefaultchannelno(programModel.getDefaultchannelno());
        } else {
            jmMain.setDefaultchannelno(null);
        }

        // 更新节目内容
        int rt = jmMainMapper.updateByPrimaryKeySelective(jmMain);

        if (rt > 0) {
            //System.out.println("进入到了这里"+programModel.getGuid());
            // 将原有素材删除,重新加入当前素材
            if (jmScMapMapper.updateByJmid(programModel.getGuid()) > 0) {
                //System.out.println("进入到了这里");
                List<ResourceFileModel> list = programModel.getJmScMaps();
                //list.addAll(programModel.getJmGgMaps());

                // 未添加素材的场合
                if (null == list || list.size() == 0) {
                    return 0;
                }
                for (ResourceFileModel map : list) {
                    map.setGuid(UUID.randomUUID().toString());
                    map.setJmid(programModel.getGuid());
                }

                rt = jmScMapMapper.insertMapList(list);
                jmScMapMapper.updateRtype();
            }
        }

//        int count = 0;
//        JmProgram jmProgram = jmProgramMapper.selectByPrimaryKey(programModel.getGuid());
//        jmProgram.setTitle(programModel.getTitle());
//        jmProgram.setMemo(programModel.getMemo());
//        count = jmProgramMapper.updateByPrimaryKey(jmProgram);
//        //保存节目素材关系
//        saveProgramFile(programModel);
//
//        if (count > 0) {
//            iLogService.log("info",
//                    "节目管理",
//                    "修改成功-【" + JSON.toJSONString(jmProgram) + "】",
//                    iUserContextService.getUserContext().getId());
//        }

        return rt;
    }

    /**
     * 根据检索条件获取节目一览
     *
     * @param apiQueryBase
     * @return
     */
    @Override
    public List<ProgramModel> findPrograms(ApiQueryBase apiQueryBase) {
        List<ProgramModel> result = jmProgramMapper.find(apiQueryBase);
//        List<ProgramFileModel> files = jmProgramFileMapMapper.findAll();
//        for (ProgramModel pm : result) {
//            pm.setFiles(new ArrayList<ProgramFileModel>());
//            for (ProgramFileModel pfm : files) {
//                if (pfm.getProgramid().equals(pm.getGuid())) {
//                    pm.getFiles().add(pfm);
//                }
//            }
//        }

        return result;
    }

    /**
     * 根据节目id查询节目
     *
     * @param id
     * @return
     */
    @Override
    public ApiResult findProgram(String id) {
        ProgramModel programModel = null;

        // 根据节目id查询节目
        JmMain jmMain = jmMainMapper.selectByPrimaryKey(id);

        if (jmMain != null) {
            programModel = new ProgramModel();
            programModel.setGuid(jmMain.getGuid());
            programModel.setTitle(jmMain.getTitle());
            programModel.setCreateuserid(jmMain.getCreateuserid());
            programModel.setSort(jmMain.getSort());

            if (StringUtils.isNoneBlank(jmMain.getDefaultchannelno())) {
                programModel.setIshaslive(true);
                programModel.setDefaultchannelno(jmMain.getDefaultchannelno());
            }

            //加载节目素材名称信息
            List<ResourceFileModel> jmScMaps = jmScMapMapper.findByJmId(id);
            List<ResourceFileModel> jmGgMaps = jmScMapMapper.findByJmidAndRtype(id);
            programModel.setJmScMaps(jmScMaps);
            programModel.setJmGgMaps(jmGgMaps);
//            //加载素材信息
//            List<ProgramFileModel> programFileModelList=new ArrayList<ProgramFileModel>()
//            for (JmScMap jmScMap:jmScMaps) {
//                    ProgramFileModel programFileModel=new ProgramFileModel();
//
//            }
        } else {
            return new ApiResult().success(AppConstant.MSG_FAILURE, "获取节目失败", null);
        }
        return new ApiResult().success(AppConstant.MSG_SUCCESS, "获取节目成功", programModel);
    }

    private void saveProgramFile(ProgramModel programModel) {
        jmProgramFileMapMapper.deleteByProgramId(programModel.getGuid());
        if (programModel.getFiles().size() > 0) {
            for (ProgramFileModel file : programModel.getFiles()) {
                JmProgramFileMap jmProgramFileMap = new JmProgramFileMap();
                jmProgramFileMap.setGuid(UUID.randomUUID().toString());
                jmProgramFileMap.setFileid(file.getFileid());
                jmProgramFileMap.setOrderindex(file.getOrderindex());
                jmProgramFileMap.setCreatetime(new Date());
                jmProgramFileMap.setProgramid(programModel.getGuid());
                jmProgramFileMapMapper.insert(jmProgramFileMap);
            }
        }
    }

    @Override
    public void saveDevProgramMap(MqPushProgramModel mqPushProgramModel) {
        if (mqPushProgramModel != null) {
            if (mqPushProgramModel.getMqSelectedDevModels() != null) {
                for (MqSelectedDevModel dev : mqPushProgramModel.getMqSelectedDevModels()) {
                    jmDevProgramMapMapper.deleteByDevsn(dev.getDevsn());
                    if (mqPushProgramModel.getMqSelectedProgramModels() != null) {
                        int orderindex = 0;
                        for (MqSelectedProgramModel program : mqPushProgramModel.getMqSelectedProgramModels()) {
                            JmDevProgramMap jmDevProgramMap = new JmDevProgramMap();
                            jmDevProgramMap.setGuid(UUID.randomUUID().toString());
                            jmDevProgramMap.setDevid(dev.getDevsn());
                            jmDevProgramMap.setProgramid(program.getId());
                            jmDevProgramMap.setCreatetime(new Date());
                            jmDevProgramMap.setOrderindex(orderindex++);
                            jmDevProgramMapMapper.insert(jmDevProgramMap);
                        }
                    }
                }
            }
        }
    }

    @Override
    public List<ProgramFileModel> findProgramFiles(String programid) {
        return jmProgramFileMapMapper.findByProgramId(programid);
    }


    // endregion

    // region << 直播流 >>

    @Override
    public ApiCode saveLive(ScLive scLive) {
        ApiCode apiCode = ApiCode.APP_100200;
        if(scLive.getChannelno().length()>3){
            //长度必须小于5
            //System.out.println("长度:"+scLive.getChannelno().length());
            apiCode = ApiCode.APP_301506;
            return apiCode;
        }
        if (!StringUtils.isNoneBlank(scLive.getChannelno())) {
            apiCode = ApiCode.APP_301504;
            return apiCode;
        }

        //判断频道是否重复
//        int isExistingChannelNo = scLiveMapper.selectCountByChannelNo(scLive.getChannelno());
//        if (isExistingChannelNo > 0) {
//            apiCode = ApiCode.APP_301505;
//            return apiCode;
//        }
        //判断频道编号是否重复
        ScLive scLive1=scLiveMapper.selectByChannelNo(scLive.getChannelno());
        if(null !=scLive1){
            //判断是否为同一个频道
            if(null == scLive.getGuid() || !scLive1.getGuid().equals(scLive.getGuid())){
                apiCode = ApiCode.APP_301505;
                return apiCode;
            }
        }

        if (!StringUtils.isNoneBlank(scLive.getGuid())) {
            insertLive(scLive);
        } else {
            updateLive(scLive);
        }

        return apiCode;
    }

    @Override
    public int insertLive(ScLive scLive) {
        if (!StringUtils.isNoneBlank(scLive.getGuid())) {
            scLive.setGuid(UUID.randomUUID().toString());
        }
        scLive.setCreatetime(new Date());
        return scLiveMapper.insert(scLive);
    }

    @Override
    public ApiCode deleteLive(String id) {
        if (scLiveMapper.deleteByPrimaryKey(id) > 0) {
            return ApiCode.APP_100200;
        } else {
            return ApiCode.APP_101400;
        }
    }

    @Override
    public int updateLive(ScLive scLive) {
        return scLiveMapper.updateByPrimaryKey(scLive);
    }

    @Override
    public List<ScLive> findLives(ApiQueryBase apiQueryBase) {
        return scLiveMapper.find(apiQueryBase);
    }

    @Override
    public ScLive findOneLive(String id) {
        return scLiveMapper.selectByPrimaryKey(id);
    }

    // endregion
}